import {
  login,
  dealerLogin,
  logout,
  getInfo,
  // getRoute,
  getDict,
  refreshDict,
  getData,
  getAuthHandle
  ,
  favorite
} from '@/api/login'

import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
// import {
//   generaMenu,
  // generateRoutesFromMenu
// } from '@/router/tools'
import {
  Message
} from 'element-ui'
import store from '../../index'

const user = {
  state: {
    token: getToken(),
    name: 'Reborn',
    roles: null,
    router: [],
    secondRouter: [],
    isLogin: false,
    userInfo: {},
    systemParam: {},
    dictMap: {},
    modelParam: [],
    regionMap: {},
    authHandle: {},
    loginForm: {},
    collectIds: [],
    collectAuthPaths: [], // 授权的菜单列表
    activeRouter: '',
    calling: false
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERINFO: (state, info) => {
      state.userInfo = info
    },
    SET_SYSPARAM: (state, param) => {
      state.systemParam = param
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ROUTER: (state, router) => {
      state.router = router
    },
    SET_SECONDROUTER: (state, secondRouter) => {
      state.secondRouter = secondRouter
    },
    SET_ISLOGIN: (state, isLogin) => {
      state.isLogin = isLogin
    },
    SET_DICTMAP: (state, map) => {
      state.dictMap = map
    },
    SET_MODELPARAM: (state, modelParam) => {
      state.modelParam = modelParam
    },
    SET_REGIONMAP: (state, map) => {
      state.regionMap = map
    },
    SET_AUTHHANDLE: (state, authHandle) => {
      state.authHandle = authHandle
    },
    SET_LOGINFORM: (state, loginForm) => {
      state.loginForm = loginForm
    },
    SET_COLLECT_IDS: (state, collectIds) => {
      state.collectIds = collectIds
    },
    // 添加收藏id
    ADD_COLLECT_ID: (state, id) => {
      const collectIds = [...state.collectIds, id]
      state.collectIds = collectIds
    },
    // 添加收藏id
    ADD_COLLECT_AUTH_PATH: (state, wPath) => {
      const collectAuthPaths = [...state.collectAuthPaths, wPath]
      state.collectAuthPaths = collectAuthPaths
    },

    // 移除收藏id
    DEL_COLLECT_ID: (state, id) => {
      const collectIds = [...state.collectIds]
      const index = collectIds.indexOf(id)
      if (index > -1) {
        collectIds.splice(index, 1)
      }
      state.collectIds = collectIds
    },
    SET_ACTIVEROUTER: (state, activeRouter) => {
      state.activeRouter = activeRouter
    },
    SET_CALLING: (state, calling) => {
      state.calling = calling
    }
  },

  actions: {
    // 登录
    Login({
      commit
    }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password.trim()
      return new Promise((resolve, reject) => {
        login({
          username: username,
          password: password
        }).then(res => {
          if (res.code == 0) {
            Message({
              message: res.msg,
              type: 'success'
            })
            setToken(res.data)

            commit('SET_TOKEN', res.data)
            store.dispatch('GetInfo')
          }
          commit('SET_TOKEN', getToken())
          commit('SET_LOGINFORM', {
            username: userInfo.username.trim(),
            password: userInfo.password.trim()
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const router = res || []
          // let userinfo = res.userinfo;
          // commit('SET_ROLES', res.roles)
          // commit('SET_NAME', userinfo.name);
          // commit('SET_USERINFO', userinfo);
          // commit('SET_AVATAR', res.avatar)
          commit('SET_ROUTER', router)
          // 设置二级菜单
          // commit('SET_SECONDROUTER', router[0].children)
          commit('SET_ISLOGIN', true)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    ChgPose({
      commit
    }) {
      return new Promise((resolve, reject) => {
        commit('SET_ISLOGIN', false)
        commit('SET_ROUTER', [])
        resolve()
      })
    },

    // 登出
    LogOut({
      commit
    }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ISLOGIN', false)
        removeToken()
        resolve()
      })
    },

    // 设置二级菜单
    SetSecondRouter({
      commit, state
    }, secondRoute) {
      return new Promise(resolve => {
        commit('SET_SECONDROUTER', secondRoute)
        resolve()
      })
    },

    SetActiveRouter({
      commit, state
    }, activeRouter) {
      return new Promise(resolve => {
        commit('SET_ACTIVEROUTER', activeRouter)
        resolve()
      })
    },

    // 数据字典
    GetDict({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getDict().then(res => {
          commit('SET_DICTMAP', res['dict'])
          commit('SET_REGIONMAP', res['region'])
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 刷新字典
    RefreshDict({ commit, state }) {
      return new Promise((resolve, reject) => {
        refreshDict().then(res => {
          commit('SET_DICTMAP', res['dict'])
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 数据字典
    GetButtonAuthHandle({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getAuthHandle().then(res => {
          var authDate = {}
          if (res != null && res.length > 0) {
            for (var i = 0; i < res.length; i++) {
              var buttonPath = res[i].CODE
              authDate[buttonPath] = true
            }
          }

          // console.log(authDate["/ordermanage/salesOrders$"])
          commit('SET_AUTHHANDLE', authDate)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 设置数据字典
    SetDictMap({
      commit
    }, dictMap) {
      return new Promise(resolve => {
        commit('SET_DICTMAP', dictMap)
        resolve()
      })
    },
    // 设置数据字典
    SetModelParam({
      commit
    }, modelParam) {
      return new Promise(resolve => {
        commit('SET_MODELPARAM', modelParam)
        resolve()
      })
    },

    // 设置区域信息
    SetRegionMap({
      commit
    }, regionMap) {
      return new Promise(resolve => {
        commit('SET_REGIONMAP', regionMap)
        resolve()
      })
    },
    // 初始化常规数据,系统参数，用户信息
    GetCommonData({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getData().then(res => {
          commit('SET_USERINFO', res.userInfo)
          commit('SET_SYSPARAM', res.systemParam)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 默认添加收藏记录
    addCollectId({ commit }, id) {
      commit('ADD_COLLECT_ID', id)
    },
    // 默认添加收藏记录
    addCollectAuthPathId({ commit }, wPath) {
      commit('ADD_COLLECT_AUTH_PATH', wPath)
    },

    // 请求服务器添加收藏
    asyncAddCollectId({ commit }, id) {
      return new Promise((resolve, reject) => {
        // commit('ADD_COLLECT_ID', id)
        // resolve(true)
        favorite(id, 10041001).then(() => {
          Message({
            message: '成功添加收藏',
            type: 'success'
          })
          commit('ADD_COLLECT_ID', id)
          resolve(true)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 移除收藏记录
    delCollectId({ commit }, id) {
      return new Promise((resolve, reject) => {
        // commit('DEL_COLLECT_ID', id)
        // resolve(true)
        favorite(id, 10041002).then(() => {
          Message({
            message: '成功移除收藏',
            type: 'success'
          })
          commit('DEL_COLLECT_ID', id)
          resolve(true)
        }).catch((error) => {
          reject(error)
        })
      })
      // commit('DEL_COLLECT_ID', id)
    },

    // 获取按钮权限
    SetAuthHandle({
      commit
    }, authHandle) {
      return new Promise(resolve => {
        commit('SET_AUTHHANDLE', authHandle)
        resolve()
      })
    },

    dealerLogin({
      commit
    }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        dealerLogin({
          username: username
        }).then(res => {
          // commit('SET_TOKEN', '')
          // commit('SET_ISLOGIN', false)
          // removeToken()
          if (res.code === 'S') {
            Message({
              message: res.message,
              type: 'success'
            })
            setToken(res.token)

            commit('SET_TOKEN', res.token)
          }
          commit('SET_TOKEN', getToken())
          resolve(res.accountFrom)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 设置通话状态
    SetCalling({
      commit
    }, calling) {
      return new Promise(resolve => {
        commit('SET_CALLING', calling)
        resolve()
      })
    }
  }
}

export default user
